from PyQt5.QtCore import QThread, QSettings, pyqtSignal
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from util.Tools import Tools
import os
import logging.config
import traceback
settings = QSettings(Tools.resource_path("config\\config.ini"), QSettings.IniFormat)
settings.setIniCodec("UTF-8")
logging.config.fileConfig(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "config\\logging.ini"))
logger = logging.getLogger("infoLogger")

class chrom_drive(QThread):
    '''
    异步自动化
    '''
    SendTxtSnal = pyqtSignal(str)
    def __init__(self):
        super().__init__()
        self.rs = None

    def inquery_image(self,list1):
        logging.info(list1)
        self.rs = list1 # [[],[]]

    def run(self):
        try:
            if self.rs != None:
                if len(self.rs)>0:
                    logging.info(self.rs)
                    self.TxtDate = ""
                    logging.info("start selenium")
                    chrome_options = Options()
                    chrome_options.add_experimental_option("debuggerAddress", settings.value("chromeDrive/chromeIp"))
                    chrome_driver = settings.value("sysconfig/driverurl")
                    self.brower = webdriver.Chrome(chrome_driver, options=chrome_options)
                    for row in self.rs:
                        self.findElementType = str(row[1]) if row[1] else None
                        self.findValue = str(row[2]) if row[2] else None
                        self.opType = str(row[3]) if row[3] else None
                        self.opValue = str(row[4]) if row[4] else None
                        self.executeOrder()
                    if self.TxtDate!="":
                        logging.info(self.TxtDate)
                        self.SendTxtSnal.emit(self.TxtDate)
                        self.TxtDate=""

            self.rs =None
        except Exception:
            logging.error(traceback.format_exc())


    def __del__(self):
        self.wait()

    def executeOrder(self):
        '''
        webdrive 自动化
        :return:
        '''
        try:
            if self.findValue != None:
                # 定位元素
                if self.findElementType == 'NAME':
                    dom = self.brower.find_element_by_name(self.findValue)
                elif self.findElementType == 'ID':
                    dom = self.brower.find_element_by_id(self.findValue)
                elif self.findElementType == 'XPATH':
                    dom = self.brower.find_element_by_xpath(self.findValue)
                elif self.findElementType == 'LINK_TEXT':
                    dom = self.brower.find_element_by_link_text(self.findValue)
                elif self.findElementType == 'PARTIAL_LINK_TEXT':
                    dom = self.brower.find_element_by_partial_link_text(self.findValue)
                elif self.findElementType == 'TAG_NAME':
                    dom = self.brower.find_element_by_tag_name(self.findValue)
                elif self.findElementType == 'CLASS_NAME':
                    dom = self.brower.find_element_by_class_name(self.findValue)
                else:
                    dom = self.brower.find_element_by_css_selector(self.findValue)
                # 执行操作
                if self.opType == 'SEND_KEY':
                    if self.opValue == 'Keys.SPACE':
                        dom.send_keys(Keys.SPACE)
                    elif self.opValue == 'Keys.TAB':
                        dom.send_keys(Keys.TAB)
                    elif self.opValue == 'Keys.ESPACE':
                        dom.send_keys(Keys.ESCAPE)
                    elif self.opValue == 'Keys.ENTER':
                        dom.send_keys(Keys.ENTER)
                    elif self.opValue == 'Keys.F1':
                        dom.send_keys(Keys.F1)
                    else:
                        dom.clear()
                        dom.send_keys(self.opValue)
                if self.opType == 'CLICK':
                    dom.click()
                if self.opType=="LEFT_CLICK":
                    Action = ActionChains(self.brower)
                    Action.click(dom).perform()
                if self.opType == "REIGHT_CLICK":
                    Action = ActionChains(self.brower)
                    Action.context_click(dom).perform()
                if self.opType == 'JS':
                    self.brower.execute_script(self.opValue,dom)
                if self.opType == "TEXT":
                    Textret = dom.text
                    logging.info(Textret)
                    self.TxtDate = self.TxtDate + str(Textret)
                if self.opType == "GET_ATTRIBUTE":
                    classret =dom.get_attribute(self.opValue)
                    logging.info(classret)
                    self.TxtDate = self.TxtDate + str(classret)
            if self.opType == 'IFRAME':
                if self.findElementType == 'ID':
                    self.brower.switch_to.frame(self.findValue)
                elif self.findElementType == 'NAME':
                    self.brower.switch_to.frame(self.findValue)
            if self.opType == 'EXIT_IFRAME':
                self.brower.switch_to.default_content()
            if self.opType == "WINDOW":
                ret = self.brower.window_handles
                self.brower.switch_to.window(ret[int(self.opValue)])
        except Exception:
            logging.error(traceback.format_exc())

